package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MovementManager {

    @DubboReference
    MovementService movementService;

    @Autowired
    OssTemplate ossTemplate;

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    CommentService commentService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    MQMovementManager mqMovementManager;

    public void save(MultipartFile[] imageContent, Movement movement) throws IOException {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.将所有的图片保存到oss上获取url
        //2.1 创建一个集合,用来存放所有图片的地址
        List<String> medias = new ArrayList();

        //2.2 上传每张图片
        if (ArrayUtil.isNotEmpty(imageContent)) {
            for (MultipartFile multipartFile : imageContent) {
                String url = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());

                //将地址放入集合
                medias.add(url);
            }
        }
        //3.给movement设置图片地址
        movement.setMedias(medias);

        //4.继续封装movement
        movement.setId(ObjectId.get());
        movement.setUserId(userId);
        //TODO 讲完内容审核之后,需要将状态改成0
        movement.setState(1);
        movement.setCreated(System.currentTimeMillis());
        movement.setSeeType(1);//该版本暂时没有这个功能

        //5.远程调用service完成保存
        movementService.save(movement);

        //6.将动态放入mq中
        rabbitTemplate.convertAndSend("tanhua.movement.state",movement.getId().toString());

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(userId,movement.getId(),MQMovementManager.MOVEMENT_PUBLISH);
    }

    //查询自己动态
    public ResponseEntity findMyMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.远程调用service查询分页数据
        PageBeanVo pageBeanVo = movementService.findMyMovementByPage(userId, pageNum, pageSize);

        //2.查询当前用户的userInfo
        UserInfo userInfo = userInfoService.findById(userId);

        //3.获取分页数据中的list,遍历,获取每个动态详情
        //3.1 创建movementVo集合
        List<MovementVo> voList = new ArrayList<>();

        //3.2 获取分页数据中的list,遍历
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //4.封装MovementVo对象(userInfo+movement),将对象放入vo集合中
                MovementVo vo = new MovementVo();

                //切记:先封装userInfo,再封装movement
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);

                //判断当前用户是否对此用户点赞过
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movement.getId()))) {
                    vo.setHasLiked(1);
                }

                voList.add(vo);
            }
        }

        //5.将vo集合设置给pageBeanVo且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    // 查询好友动态
    public ResponseEntity findFriendMovementByPage(Integer pageNum, Integer pageSize) {
        //1.获取登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用service查询好友动态数据
        PageBeanVo pageBeanVo = movementService.findFriendMovementByPage(userId, pageNum, pageSize);

        //3.获取动态数据list,遍历,获取每个动态,通过动态发布者id查询userInfo
        //3.1 创建movementVo集合
        List<MovementVo> voList = new ArrayList<>();

        //3.2 获取分页数据list,遍历
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                //3.3 获取每个动态发布者id 查询userInfo
                UserInfo userInfo = userInfoService.findById(movement.getUserId());


                //4.封装MovementVo对象,放入vo集合中
                MovementVo vo = new MovementVo();

                //先userInfo 后movement
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);

                //判断当前用户是否对此用户点赞过
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movement.getId()))) {
                    vo.setHasLiked(1);
                }

                voList.add(vo);
            }
        }

        //5.将vo集合设置给pageBeanVo且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    //查看推荐动态
    public ResponseEntity findRecommendMovementByPage(Integer pageNum, Integer pageSize) {
        //1.获取当前用户id
        Long userId = UserHolder.get().getId();

        //2.远程调用动态service获取pageBeanVo
        PageBeanVo pageBeanVo = movementService.findRecommendMovementByPage(userId, pageNum, pageSize);

        //3.获取pageBeanVo中动态集合
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();

        //4.遍历动态集合,获取每个动态,获取动态发布人的userInfo,
        List<MovementVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            items.forEach(movement -> {
                //获取动态发布人的userInfo,
                UserInfo userInfo = userInfoService.findById(movement.getUserId());

                //创建MovementVo,封装userInfo和动态,
                MovementVo vo = new MovementVo();
                vo.setUserInfo(userInfo);
                vo.setMovement(movement);

                //判断当前用户是否对此动态点赞过
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,movement.getId()))) {
                    vo.setHasLiked(1);
                }

                //判断当前用户是否对此动态喜欢过
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,userId,movement.getId()))) {
                    vo.setHasLoved(1);
                }

                //将每个vo放入voList中
                voList.add(vo);
            });
        }

        //6.给pageBeanVo设置voList,且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    // 点赞
    public ResponseEntity movementLike(String publishId) {
        //1.获取当前登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用movementservice查询对象
        Movement movement = movementService.findById(new ObjectId(publishId));

        //3.封装comment对象
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setUserId(userId);
        comment.setPublishUserId(movement.getUserId());

        //4.远程调用commentservice进行保存
        int count = commentService.save(comment);

        //5.标记当前用户对这条动态点过赞(redis)
        //  key : movement_like:用户id_动态id
        // value: 值都是1
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,publishId),"1");

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(userId,movement.getId(),MQMovementManager.MOVEMENT_LIKE);

        //6.返回最新的操作数量
        return ResponseEntity.ok(count);

    }

    // 取消点赞
    public ResponseEntity movementDislike(ObjectId publishId) {
        //1.获取当前登陆者id
        Long userId = UserHolder.get().getId();
        //2.远程service完成删除操作
        int count = commentService.remove(userId, publishId, 1);

        //3.删除redis中点赞的标记
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LIKE,userId,publishId));

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(userId,publishId,MQMovementManager.MOVEMENT_DISLIKE);

        //4.将最新的数字返回
        return ResponseEntity.ok(count);
    }

    public ResponseEntity movementLove(String publishId) {
        //1.获取当前登陆者id
        Long userId = UserHolder.get().getId();

        //2.远程调用movementservice查询对象
        Movement movement = movementService.findById(new ObjectId(publishId));

        //3.封装comment对象
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(3); //喜欢  : 3
        comment.setUserId(userId);
        comment.setPublishUserId(movement.getUserId());

        //4.远程调用commentservice进行保存
        int count = commentService.save(comment);

        //5.标记当前用户对这条动态点过 喜欢
        //  key : movement_like:用户id_动态id
        // value: 值都是1
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,userId,publishId),"1");

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(userId,movement.getId(),MQMovementManager.MOVEMENT_LOVE);

        //6.返回最新的操作数量
        return ResponseEntity.ok(count);
    }

    public ResponseEntity movementUnlove(ObjectId publishId) {
        //1.获取当前登陆者id
        Long userId = UserHolder.get().getId();
        //2.远程service完成删除操作
        int count = commentService.remove(userId, publishId, 3);

        //3.删除redis中点赞的标记
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.MOVEMENT_LOVE,userId,publishId));

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(userId,publishId,MQMovementManager.MOVEMENT_DISLOVE);

        //4.将最新的数字返回
        return ResponseEntity.ok(count);
    }

    //查看单条动态
    public ResponseEntity findById(String publishId) {
        //1. 远程调用service获取movement对象
        Movement movement = movementService.findById(new ObjectId(publishId));

        //2.从movement中获取发布人id,远程调用service获取userInfo
        UserInfo userInfo = userInfoService.findById(movement.getUserId());

        //3.封装MovementVo对象且返回
        MovementVo vo = new MovementVo();

        //先封装userInfo,在封装movement
        vo.setUserInfo(userInfo);
        vo.setMovement(movement);

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(UserHolder.get().getId(),movement.getId(),MQMovementManager.MOVEMENT_BROWSE);

        return ResponseEntity.ok(vo);
    }

    // 查看评论列表
    public ResponseEntity findCommentByPage(String publishId, Integer pageNum, Integer pageSize) {
        //1.远程调用service进行分页查询
        PageBeanVo pageBeanVo = commentService.findByPage(new ObjectId(publishId), pageNum, pageSize);

        //2.获取pageBeanVo中集合(评论),遍历此集合,获取每个评论发布人的userInfo,将userInfo和评论封装成vo对象,将每个vo放入新集合中
        //2.0 创建vo集合
        List<CommentVo> voList = new ArrayList<>();

        //2.1 获取pageBeanVo中集合(评论),遍历此集合
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            items.forEach(e->{
                //2.2 获取每个评论发布人的userInfo
                UserInfo userInfo = userInfoService.findById(e.getUserId());

                //2.3 将userInfo和评论封装成vo对象,
                CommentVo vo = new CommentVo();

                vo.setId(e.getId().toString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(e.getContent());
                vo.setCreateDate(DateUtil.formatDateTime(new Date(e.getCreated())));
                //TODO 自己完成对评论的点赞
                vo.setLikeCount(e.getLikeCount());

                //2.4 将每个vo放入新集合中
                voList.add(vo);
            });
        }

        //3.给pageBeanVo设置封装后集合,且返回
        pageBeanVo.setItems(voList);

        return ResponseEntity.ok(pageBeanVo);
    }

    // 发表评论
    public ResponseEntity saveMovementComment(String publishId, String content) {
        //1.远程调用movementService查询动态对象
        Movement movement = movementService.findById(new ObjectId(publishId));

        //2.封装Comment对象
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(publishId));
        comment.setContent(content);
        comment.setCommentType(2);
        comment.setUserId(UserHolder.get().getId());
        comment.setPublishUserId(movement.getUserId());

        //3.远程调用service进行保存
        int count = commentService.save(comment);

        //最后.将用户的操作存入mq中
        mqMovementManager.sendMovement(UserHolder.get().getId(),movement.getId(),MQMovementManager.MOVEMENT_COMMENT);

        return ResponseEntity.ok(count);
    }
}